package nl.project.system;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.project.data.Employee;
import nl.project.data.Parent;
import nl.project.data.Student;
import nl.project.data.Teacher;
import nl.project.data.User;
import nl.project.data.controller.MembersDAO;

import com.google.appengine.api.datastore.EntityNotFoundException;

@SuppressWarnings("serial")
public class LoginChecker extends HttpServlet {

	/*
	 * User gets here when navigating to the 'root' page. If user has 
	 * not yey logged in, redirect the user to the login page. Else, 
	 * redirect to the user's own Dashboard.
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		// Check if user has logged in earlier.
		if (session.getAttribute("user") != null) {
			resp.sendRedirect("/dashboard");
		} else {
			resp.sendRedirect("/login.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// If more or less than three parameters are send, something has gone wrong.
		// Only 'code', 'password' and 'type' ought to be send.
		if (req.getParameterMap().size() == 3) {
			String[] userInfo = validateLoginValues(req);
			System.out.println(userInfo[0]);
			System.out.println(userInfo[1]);
			int userId = Integer.valueOf(req.getParameter("code"));
			boolean isValidated = Boolean.valueOf(userInfo[0]);
			if (isValidated) { // Validation successful!
				String userType = userInfo[1];
				HttpSession session = req.getSession();
				try {
					if (userType.equals("student")) {
						User user = new Student(userId);
						session.setAttribute("user", user);
					} else if (userType.equals("parent")) {
						User user = new Parent(userId);
						session.setAttribute("user", user);
					} else if (userType.equals("teacher")) {
						User user = new Teacher(userId);
						session.setAttribute("user", user);
					} else if (userType.equals("employee")) {
						User user = new Employee(userId);
						session.setAttribute("user", user);
					} else {
						// ERROR! :P
					}
				} catch (EntityNotFoundException e) {
					// ERROR! :P
				}
				session.setAttribute("userType", userType);
				session.setAttribute("id", req.getParameter("code"));
				resp.sendRedirect("/dashboard");
			} else { // Validation failed. Try again.
				req.setAttribute("error", userInfo[1]);
				req.getRequestDispatcher("/login.jsp").forward(req, resp);
			}
		} else { // Apparently no input values. User has come here some other way. So send the user back.
			doGet(req, resp);
		}
	}

	private String[] validateLoginValues(HttpServletRequest req) {
		boolean isValidated = false;
		String[] userInfo = new String[2];
		
		// Check if the right parameters are send
		if (req.getParameter("code") != null && req.getParameter("code") != "" && 
				req.getParameter("password") != null && req.getParameter("password") != "") {			
			try {
				int code = Integer.parseInt(req.getParameter("code"));
				String password = req.getParameter("password");
				String type = req.getParameter("type");
				if (MembersDAO.authenticate(code, password, type)) {
					isValidated = true;
					userInfo[1] = req.getParameter("type");					
				} else {
					userInfo[1] = "Gebruiker niet gevonden. Kloppen de ingevulde gegevens?";
				}
			} catch (NumberFormatException e) {
				userInfo[1] = "Ingevulde code is niet geldig.";
			} catch (EntityNotFoundException e) {
				userInfo[1] = "Gebruiker niet gevonden. Kloppen de ingevulde gegevens?";
			}
		} else {
			userInfo[1] = "Er is iets mis gegaan. Zijn alle velden ingevuld?";
		}
		userInfo[0] = String.valueOf(isValidated);
		return userInfo;
	}
}